import jwt
from django.conf import settings
from django.utils import timezone

def generate_token(user):
    """生成Token"""
    now = timezone.now()
    payload = {
        'user_phone':user.phone,
        'user_username':user.username,
        'exp': now + timezone.timedelta(hours=1) # 1小时后过期
    }

    token = jwt.encode(payload,key=settings.SECRET_KEY,algorithm='HS256')
    return token


def varify_token(token):
    """验证Token"""
    try:
        payload = jwt.decode(token,key=settings.SECRET_KEY,algorithms=['HS256'])
        return payload,1
    except jwt.ExpiredSignatureError:
        return "token已过期",0
    except jwt.InvalidTokenError:
        return "无效的token",0